<template>
  <div>
    <div :class="{hidden: isHidden}">
      <div class="app-container">
        <!--        搜索面板-->
        <el-row>
          <search-panel
            search
            special-create
            application
            :item-name="itemName"
            :item-number="totalNum"
            @on-search="onSearch"
            @auto-create="toNew"
            @manual-create="manualCreate"
            @import="importFrom"
            @search-clear="searchClear"
          />
        </el-row>
        <!--       数据列表 -->
        <el-row>
          <el-table
            v-loading="listLoading"
            :data="list"
            :stripe="true"
            element-loading-text="Loading"
            :border="false"
            :header-cell-style="{color:'black'}"
            fit
            highlight-current-row
          >
            <!--          <el-table v-loading="listLoading" :data="this.$store.state.slist" :stripe="true" element-loading-text="Loading" :border="false" :header-cell-style="{color:'black'}" fit highlight-current-row>-->
            <!--            第一列 名称-->
            <el-table-column :label="$t('name')" align="center" width="238px">
              <template v-slot="scope">
                {{ scope.row.app_name }}
              </template>
            </el-table-column>
            <!--            第二列 描述-->
            <el-table-column :label="$t('description')" align="center">
              <template v-slot="scope">
                {{ scope.row.app_description }}
              </template>
            </el-table-column>
            <!-- 如果是管理员，则显示创建者 -->
            <el-table-column v-if="this.$store.getters.isAdmin()" :label="$t('creator')" width="119px" align="center">
              <template v-slot="scope">
                {{ scope.row.creator_name }}
              </template>
            </el-table-column>
            <!--            第三列 更新时间-->
            <el-table-column align="center" :label="$t('create_update_time')" width="238px">
              <template v-slot="scope">
                <div>
                  <!-- {{ scope.row.instruction }} -->
                  {{ stringToDate(scope.row.created_time) }}
                </div>
                <div>
                  {{ stringToDate(scope.row.update_time) }}
                </div>
              </template>
            </el-table-column>
            <!--            第四列 操作-->
            <el-table-column align="center" :label="$t('operation')" width="119px" fixed="right">
              <template v-slot="scope">
                <div>
                  <!-- <div style="display: flex; justify-content: center; margin-bottom: 0;">
                    <div style="margin-right: 10px;">
                      <a href="javascript:void(0)" class="font-blue" @click="toEdit(scope.row.id)">{{ $t('edit') }}</a>
                    </div>
                    <div>
                      <a href="javascript:void(0)" class="font-blue" @click="toDelete(scope.row.id)">{{ $t('delete') }}</a>
                    </div>
                  </div> -->
                  <div style="display: flex; justify-content: center;">
                    <div style="margin-right: 10px;">
                      <a href="javascript:void(0)" class="font-blue" @click="toDetail(scope.row.id)">{{ $t('detail') }}</a>
                    </div>
                    <div>
                      <a href="javascript:void(0)" class="font-blue" @click="toRun(scope.row.id)">{{ $t('run') }}</a>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <!--        页数-->
        <el-row>
          <el-pagination
            align="center"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="totalNum"
            layout="prev, pager, next, jumper"
            @current-change="freshList"
          />
        </el-row>
      </div>
    </div>

    <div :class="{hidden: !isHidden}">
      <router-view />
    </div>

    <div :class="{hidden: !showInputDialog}">
      <el-dialog
        :visible.sync="showInputDialog"
        :title="$t('import_template')"
        width="30%"
        @closed="inputId = ''"
      >
        <el-input
          v-model="inputId"
          :placeholder="$t('template_import_tips')"
          clearable
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="showInputDialog = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="handleInputConfirm">{{ $t('confirm') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import SearchPanel from '@/components/SearchPanel/index.vue'
// import store from '@/store'
import { getAppList, importTemplate, saveWorkflowAsApp} from '@/api/app'
import { getUserName } from '@/api/user'

export default {
  components: {
    SearchPanel
  },
  data() {
    return {
      list: [],
      searchQuery: '', // 搜索的关键词
      listLoading: true,
      pageSize: 15,
      totalNum: 0,
      pageNum: 0,
      currentPage: 1,
      hidden: true,
      showInputDialog: false,
      inputId: '',
      // 当前登录用户的id
      userId: undefined,
      // 用于获取creator_id对应的username
      userMap: {},
      // 用于三极路由
      isHidden: false,
      importApp:{
        app_name: "默认应用名称",
        app_description: "默认应用描述",
        creator_id: "",
        script: ""
      }
    }
  },
  computed: {
    store() {
      return store
    },
    itemName() {
      if (this.searchQuery && this.searchQuery !== '') {
        return this.$t('n') + this.$t('with') + '“' + this.searchQuery + '”' + this.$t('app')
      } else {
        return this.$t('n') + this.$t('app')
      }
    }
  },
  created() {
    // 获取当前登录用户的id
    this.userId = this.$store.getters.id
    this.freshList(1)
    this.listLoading = false
    if (this.$route.path !== '/app_management/index') this.isHidden = true
  },
  methods: {
    // 更新列表
    freshList(nowPage) {
      this.listLoading = true
      // 获取工作流
      if (this.$store.getters.isAdmin()) {
        getAppList(nowPage, this.pageSize, null, this.searchQuery).then(response => {
          // 获取应用当前页和总个数
          this.list = response.data
          this.totalNum = response.total_count
          this.pageNum = Math.ceil(this.totalNum / this.pageSize)
          this.listLoading = false
        }).catch(error => {
          console.log(error)
          this.$message({
            message: this.$t('acquisition_failure'),
            type: 'error'
          })
          this.listLoading = false
        })
      } else {
        getAppList(nowPage, this.pageSize, this.userId, this.searchQuery).then(response => {
          // 获取工作流的总个数
          this.list = response.data
          // 更新分页信息
          this.totalNum = response.total_count
          this.pageNum = Math.ceil(this.totalNum / this.pageSize)
          this.listLoading = false
        }).catch(error => {
          console.log(error)
          this.$message({
            message: this.$t('acquisition_failure'),
            type: 'error'
          })
          this.listLoading = false
        })
      }
      this.currentPage = nowPage
    },

    // 详情
    toDetail(id) {
      this.$router.push({ path: '/app_management/index/details/', query: { id: id }})
    },
    // 搜索
    onSearch(key) {
      this.searchQuery = key
      this.freshList(1)
    },
    // 清空搜索条件
    searchClear() {
      this.searchQuery = ''
      this.freshList(1)
    },
    // 运行
    toRun(id) {
      this.$router.push({ path: `/app_management/index/details/chatExecutingUser`, query: { id: id }})
    },
    // 新建
    toNew() {
      this.$router.push({ path: '/app_management/index/new', query: { id: -1 }})
    },
    // 手动创建
    manualCreate() {
      this.$router.push({ path: '/app_management/index/new', query: { id: -2 }})
    },
    importFrom() {
      this.showInputDialog = true
    },
    handleInputConfirm() {
      if (!this.inputId.trim()) {
        // 检查 inputValue 是否为空或只包含空格
        this.$message({
          type: 'warning',
          message: '请输入有效的ID'
        });
        return; // 阻止进一步执行
      }

      // 如果 inputId 不为空，执行导入流程
      this.showInputDialog = false
      this.handleImport(this.inputId)
      this.inputId = ''; // 重置输入框内容
    },

    handleImport(inputId) {
      // 将inputId转换为整数id
      const id = parseInt(inputId.trim());
      console.log(id)
      console.log(this.$store.getters.template_server)
      // 检查id是否为有效数字，或者ifProcess是否不为空
      if (!isNaN(id) && this.$store.getters.template_server_available) {
        const formData = new FormData();
        formData.append('template_id', id);
        // formData.append('ifProcess', ifProcess);
        formData.append('tcenter_url', this.$store.getters.template_server);
        console.log("formData", formData)
        // 调用导入接口
        importTemplate(formData).then(response => {
          console.log(response)
          // 将app_name, app_description、creator_id、script加入到importApp中
          this.importApp.creator_id = this.userId
          this.importApp.script = response
          // 导入应用的名称为：xxxx-xx-xx(导入日期)_xx-xx(导入时间)_导入应用。例如：2025-03-10_13-55_导入应用
          const now = new Date();
          const year = now.getFullYear();
          const month = String(now.getMonth() + 1).padStart(2, '0');
          const day = String(now.getDate()).padStart(2, '0');
          const hours = String(now.getHours()).padStart(2, '0');
          const minutes = String(now.getMinutes()).padStart(2, '0');
          this.importApp.app_name = `${year}-${month}-${day}_${hours}-${minutes}_导入应用`;
          saveWorkflowAsApp(this.importApp).then(response => {
            console.log(response)
            if(response.message = "app created successfully"){
              this.$message({
                message: '导入成功',
                type: 'success'
              });
            }
            else{
              this.$message({
                message: '导入失败',
                type: 'error'
              });
            }
          })
          const newAppScript = response
        }).catch(error => {
          console.log(error)
          this.$message({
            message: '导入失败',
            type: 'error'
          });
        })
      } else {
        // 如果id不是有效数字或ifProcess为空，则显示警告消息
        this.$message({
          type: 'warning',
          message: '请输入有效值或选择一个处理'
        });
      }
    },

    // 将Wed, 28 Aug 2024 19:59:45 GMT字符串，转换为2024-08-28 19:59:45
    stringToDate(dateString) {
      if (typeof dateString !== 'string') {
        // 创建 Date 对象
        const date = new Date(dateString['$date'])

        // 获取年份
        const year = date.getUTCFullYear()
        // 获取月份，注意要加 1，因为月份是从 0 开始的
        const month = String(date.getUTCMonth() + 1).padStart(2, '0')
        // 获取日期
        const day = String(date.getUTCDate()).padStart(2, '0')
        // 获取小时
        const hours = String(date.getUTCHours()).padStart(2, '0')
        // 获取分钟
        const minutes = String(date.getUTCMinutes()).padStart(2, '0')
        // 获取秒
        const seconds = String(date.getUTCSeconds()).padStart(2, '0')

        // 组合成指定格式的字符串
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      // 正则表达式来匹配日期和时间的各个部分
      const regex = /^(\w+),\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d{2}):(\d{2}):(\d{2})\s+GMT$/
      const parts = dateString.match(regex)

      if (!parts) {
        throw new Error('Invalid date string format')
      }

      // 从匹配结果中提取年、月、日等
      const [, , day, monthShort, year, hour, minute, second] = parts

      // 映射月份缩写到数字（注意月份是从0开始的）
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
      const monthIndex = months.indexOf(monthShort)
      if (monthIndex === -1) {
        throw new Error('Invalid month in date string')
      }

      // 创建一个新的Date对象
      const date = new Date(Date.UTC(year, monthIndex, day, hour, minute, second))

      // 格式化日期时间为YYYY-MM-DD HH:MM:SS
      const formattedDate = `${date.getUTCFullYear()}-${(date.getUTCMonth() + 1).toString().padStart(2, '0')}-${date.getUTCDate().toString().padStart(2, '0')} ${date.getUTCHours().toString().padStart(2, '0')}:${date.getUTCMinutes().toString().padStart(2, '0')}:${date.getUTCSeconds().toString().padStart(2, '0')}`

      return formattedDate
    }
  }
}
</script>

<style>
.hidden {
  display: none;
}
.app-container{
  padding: 20px;
}
.font-blue {
  color: #66b1ff
}
</style>
